<template>
  <div class="article-publish">
    <div class="publish-header">
      <button class="back-btn" @click="$emit('back')">
        <i class="fas fa-arrow-left"></i>
        <span>返回列表</span>
      </button>
      <div class="publish-actions">
        <button class="preview-btn" @click="togglePreview">
          <i class="far fa-eye"></i>
          {{ isPreview ? '编辑' : '预览' }}
        </button>
        <button class="draft-btn" @click="saveDraft" :disabled="!canSave">
          <i class="far fa-save"></i>
          保存草稿
        </button>
        <button class="publish-btn" @click="publishArticle" :disabled="!canPublish">
          <i class="fas fa-paper-plane"></i>
          发布文章
        </button>
      </div>
    </div>

    <div class="publish-content" :class="{ 'preview-mode': isPreview }">
      <!-- 编辑模式 -->
      <div v-show="!isPreview" class="edit-mode">
        <div class="form-group">
          <input 
            type="text" 
            v-model="article.title" 
            placeholder="请输入文章标题..."
            class="title-input"
            @input="validateForm"
          >
        </div>

        <div class="form-group">
          <div class="tags-input">
            <div class="selected-tags">
              <span 
                v-for="tag in article.tags" 
                :key="tag" 
                class="tag"
                @click="removeTag(tag)"
              >
                #{{ tag }}
                <i class="fas fa-times"></i>
              </span>
            </div>
            <input 
              type="text" 
              v-model="newTag" 
              placeholder="输入标签，按回车添加..."
              @keydown.enter.prevent="addTag"
              @blur="addTag"
            >
          </div>
        </div>

        <div class="form-group">
          <textarea 
            v-model="article.excerpt" 
            placeholder="请输入文章摘要..."
            class="excerpt-input"
            @input="validateForm"
          ></textarea>
        </div>

        <div class="editor-container">
          <div class="editor-toolbar">
            <button @click="insertMarkdown('bold')" title="加粗">
              <i class="fas fa-bold"></i>
            </button>
            <button @click="insertMarkdown('italic')" title="斜体">
              <i class="fas fa-italic"></i>
            </button>
            <button @click="insertMarkdown('heading')" title="标题">
              <i class="fas fa-heading"></i>
            </button>
            <button @click="insertMarkdown('link')" title="链接">
              <i class="fas fa-link"></i>
            </button>
            <button @click="insertMarkdown('image')" title="图片">
              <i class="fas fa-image"></i>
            </button>
            <button @click="insertMarkdown('code')" title="代码">
              <i class="fas fa-code"></i>
            </button>
            <button @click="insertMarkdown('quote')" title="引用">
              <i class="fas fa-quote-right"></i>
            </button>
            <button @click="insertMarkdown('list')" title="列表">
              <i class="fas fa-list"></i>
            </button>
          </div>
          <textarea 
            v-model="article.content" 
            placeholder="请输入文章内容，支持 Markdown 格式..."
            class="content-input"
            @input="validateForm"
          ></textarea>
        </div>
      </div>

      <!-- 预览模式 -->
      <div v-show="isPreview" class="preview-mode">
        <article class="preview-content">
          <h1 class="preview-title">{{ article.title || '无标题' }}</h1>
          <div class="preview-meta">
            <span class="preview-tags">
              <span v-for="tag in article.tags" :key="tag" class="tag">#{{ tag }}</span>
            </span>
            <span class="preview-time">{{ new Date().toLocaleString() }}</span>
          </div>
          <p class="preview-excerpt">{{ article.excerpt || '暂无摘要' }}</p>
          <div class="preview-body markdown-body" v-html="renderedContent"></div>
        </article>
      </div>
    </div>
  </div>
</template>

<script>
import marked from 'marked'
import DOMPurify from 'dompurify'

export default {
  name: 'ArticlePublish',
  data() {
    return {
      isPreview: false,
      newTag: '',
      article: {
        title: '',
        tags: [],
        excerpt: '',
        content: '',
        date: new Date().toLocaleString(),
        readTime: 0
      },
      canSave: false,
      canPublish: false
    }
  },
  computed: {
    renderedContent() {
      if (!this.article.content) return ''
      const rawHtml = marked(this.article.content)
      return DOMPurify.sanitize(rawHtml)
    }
  },
  methods: {
    togglePreview() {
      this.isPreview = !this.isPreview
    },
    validateForm() {
      // 检查必填字段
      const hasTitle = this.article.title.trim().length > 0
      const hasContent = this.article.content.trim().length > 0
      const hasTags = this.article.tags.length > 0

      this.canSave = hasTitle || hasContent // 只要有标题或内容就可以保存草稿
      this.canPublish = hasTitle && hasContent && hasTags // 发布需要所有必填字段
    },
    addTag() {
      if (!this.newTag.trim()) return
      const tag = this.newTag.trim()
      if (!this.article.tags.includes(tag)) {
        this.article.tags.push(tag)
        this.validateForm()
      }
      this.newTag = ''
    },
    removeTag(tag) {
      const index = this.article.tags.indexOf(tag)
      if (index > -1) {
        this.article.tags.splice(index, 1)
        this.validateForm()
      }
    },
    insertMarkdown(type) {
      const textarea = document.querySelector('.content-input')
      const start = textarea.selectionStart
      const end = textarea.selectionEnd
      const selectedText = this.article.content.substring(start, end)
      let insertText = ''

      switch (type) {
        case 'bold':
          insertText = `**${selectedText || '加粗文本'}**`
          break
        case 'italic':
          insertText = `*${selectedText || '斜体文本'}*`
          break
        case 'heading':
          insertText = `\n## ${selectedText || '标题'}\n`
          break
        case 'link':
          insertText = `[${selectedText || '链接文本'}](url)`
          break
        case 'image':
          insertText = `![${selectedText || '图片描述'}](图片URL)`
          break
        case 'code':
          insertText = `\`\`\`\n${selectedText || '代码块'}\n\`\`\``
          break
        case 'quote':
          insertText = `\n> ${selectedText || '引用文本'}\n`
          break
        case 'list':
          insertText = `\n- ${selectedText || '列表项'}\n`
          break
      }

      this.article.content = 
        this.article.content.substring(0, start) + 
        insertText + 
        this.article.content.substring(end)

      // 更新光标位置
      this.$nextTick(() => {
        const newCursorPos = start + insertText.length
        textarea.focus()
        textarea.setSelectionRange(newCursorPos, newCursorPos)
      })
    },
    saveDraft() {
      if (!this.canSave) return
      // TODO: 实现保存草稿逻辑
      console.log('保存草稿:', this.article)
      this.$emit('save-draft', { ...this.article })
    },
    publishArticle() {
      if (!this.canPublish) return
      // 计算阅读时间（假设每分钟阅读 300 字）
      const wordCount = this.article.content.length
      this.article.readTime = Math.ceil(wordCount / 300)
      
      // TODO: 实现发布文章逻辑
      console.log('发布文章:', this.article)
      this.$emit('publish', { ...this.article })
    }
  }
}
</script>

<style scoped>
.article-publish {
  background: var(--card-bg);
  border-radius: 24px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.5);
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.publish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  background: var(--primary-light);
  color: white;
  border-radius: 50px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: var(--transition);
}

.back-btn:hover {
  background: var(--primary);
  transform: translateX(-2px);
}

.publish-actions {
  display: flex;
  gap: 12px;
}

.preview-btn,
.draft-btn,
.publish-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: var(--transition);
}

.preview-btn {
  background: var(--card-bg);
  color: var(--dark);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.preview-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.draft-btn {
  background: var(--gray-light);
  color: var(--dark);
}

.draft-btn:hover:not(:disabled) {
  background: var(--gray);
  color: white;
}

.publish-btn {
  background: var(--primary);
  color: white;
}

.publish-btn:hover:not(:disabled) {
  background: var(--primary-light);
  transform: translateY(-2px);
}

.preview-btn:disabled,
.draft-btn:disabled,
.publish-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.publish-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.title-input {
  width: 100%;
  font-size: 2rem;
  padding: 10px;
  border: none;
  border-bottom: 2px solid rgba(0, 0, 0, 0.1);
  background: transparent;
  color: var(--dark);
  transition: var(--transition);
}

.title-input:focus {
  outline: none;
  border-color: var(--primary);
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  background: var(--card-bg);
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  background: var(--primary-light);
  color: white;
  border-radius: 50px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: var(--transition);
}

.tag:hover {
  background: var(--primary);
}

.tag i {
  font-size: 0.8rem;
}

.tags-input input {
  flex: 1;
  min-width: 200px;
  border: none;
  background: transparent;
  padding: 4px;
  color: var(--dark);
}

.tags-input input:focus {
  outline: none;
}

.excerpt-input {
  width: 100%;
  min-height: 80px;
  padding: 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  resize: vertical;
  font-size: 1rem;
  background: var(--card-bg);
  color: var(--dark);
  transition: var(--transition);
}

.excerpt-input:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
}

.editor-toolbar {
  display: flex;
  gap: 4px;
  padding: 8px;
  background: var(--gray-light);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.editor-toolbar button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: transparent;
  color: var(--dark);
  border-radius: 4px;
  cursor: pointer;
  transition: var(--transition);
}

.editor-toolbar button:hover {
  background: rgba(0, 0, 0, 0.05);
}

.content-input {
  flex: 1;
  width: 100%;
  min-height: 400px;
  padding: 20px;
  border: none;
  resize: none;
  font-size: 1rem;
  line-height: 1.6;
  background: var(--card-bg);
  color: var(--dark);
  font-family: monospace;
}

.content-input:focus {
  outline: none;
}

/* 预览模式样式 */
.preview-mode {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.preview-title {
  font-size: 2.5rem;
  color: var(--dark);
  margin-bottom: 20px;
  line-height: 1.3;
}

.preview-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  color: var(--gray);
  font-size: 0.9rem;
}

.preview-tags {
  display: flex;
  gap: 8px;
}

.preview-excerpt {
  font-size: 1.2rem;
  color: var(--gray);
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.preview-body {
  color: var(--dark);
  line-height: 1.8;
  font-size: 1.1rem;
}

/* Markdown 样式 */
.markdown-body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body h1 { font-size: 2em; }
.markdown-body h2 { font-size: 1.5em; }
.markdown-body h3 { font-size: 1.25em; }

.markdown-body p {
  margin-top: 0;
  margin-bottom: 16px;
}

.markdown-body code {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27,31,35,0.05);
  border-radius: 3px;
  font-family: monospace;
}

.markdown-body pre {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
}

.markdown-body pre code {
  padding: 0;
  margin: 0;
  background-color: transparent;
  border: 0;
}

.markdown-body blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0 0 16px 0;
}

.markdown-body img {
  max-width: 100%;
  box-sizing: border-box;
  border-radius: 8px;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 2em;
  margin-top: 0;
  margin-bottom: 16px;
}

.markdown-body a {
  color: var(--primary);
  text-decoration: none;
}

.markdown-body a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .article-publish {
    padding: 15px;
    border-radius: 0;
  }

  .publish-header {
    flex-direction: column;
    gap: 15px;
  }

  .publish-actions {
    width: 100%;
    justify-content: space-between;
  }

  .preview-btn,
  .draft-btn,
  .publish-btn {
    flex: 1;
    justify-content: center;
  }

  .title-input {
    font-size: 1.5rem;
  }

  .preview-title {
    font-size: 2rem;
  }

  .editor-toolbar {
    overflow-x: auto;
    padding: 8px 4px;
  }

  .editor-toolbar button {
    width: 28px;
    height: 28px;
  }

  .content-input {
    min-height: 300px;
    padding: 15px;
  }
}
</style> 